package com.potevio.simulator.init;


import com.potevio.simulator.common.MsgBean;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description:报文字段属性实体类
 * @Date 2021/5/7  15:11
 * @Author zyd
 * @Version 1.0
 */
@Component
public class ApplicationStartQuartzJobListener implements ApplicationRunner {

    /**
     * 全局变量，用来存储报文字段类型和长度
     */
    public static ConcurrentHashMap<String, LinkedHashMap<String, MsgBean>> chm = new ConcurrentHashMap<String, LinkedHashMap<String, MsgBean>>();

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        initXml2Map();
    }

    /**
     * 将xml中的配置初始化到全局变量map中
     * @author : zyd
     * @date : 2021/5/7 15:12
     * @return : void
     */
    private void initXml2Map() throws Exception {
        // 1.创建Reader对象
        SAXReader reader = new SAXReader();
        // 2.加载xml
        Resource resources = new ClassPathResource("msgconfig.xml");
        InputStream inputStream = resources.getInputStream();
        Document document = reader.read(inputStream);
        // 3.获取根节点
        Element rootElement = document.getRootElement();
        // 4.迭代根节点
        Iterator iterator = rootElement.elementIterator();
        while (iterator.hasNext()){
            Element stu = (Element) iterator.next();
            // 获取节点id属性值
            String protocolId = stu.attribute("id").getValue();
            // 获取protocol节点所有属性，获取属性值
//            List<Attribute> attributes = stu.attributes();
//            for (Attribute attribute : attributes) {
//                System.out.println(attribute.getValue());
//            }
            // 遍历protocol所有子节点
            Iterator iterator1 = stu.elementIterator();
            LinkedHashMap<String, MsgBean> map = new LinkedHashMap<String, MsgBean>();
            while (iterator1.hasNext()){
                MsgBean msgBean = new MsgBean();
                Element stuChild = (Element) iterator1.next();
                msgBean.setId(stuChild.attribute("id").getValue());
                msgBean.setName(stuChild.attribute("name").getValue());
                msgBean.setType(stuChild.attribute("type").getValue());
                msgBean.setLength(stuChild.attribute("length").getValue());
                msgBean.setValue(stuChild.attribute("value").getValue());
                map.put(stuChild.attribute("id").getValue(), msgBean);
            }
            ApplicationStartQuartzJobListener.chm.put(protocolId, map);
        }
    }

}
